﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;

namespace LRT.Syndication.Data
{
    internal partial class DataProvider
    {
        #region instance

        static DataProvider instance;
        static object lockObj = new object();
        public static DataProvider Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObj)
                    {
                        if (instance == null)
                        {

                            instance = new DataProvider();
                        }
                    }
                }
                return instance;
            }
        }

        #endregion

        #region connection

        static IDbConnection GetDbConnection()
        {
            var connection = SqlClientFactory.Instance.CreateConnection();
            //connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["rssConnectionString"].ConnectionString;
            connection.ConnectionString = "Data Source=127.0.0.1;Initial Catalog=Nebula;Persist Security Info=True;User ID=sa;Password=123456";
            connection.Open();
            return connection;
        }

        #endregion

        #region Paging
        static string BuildPageSQL(string sql, string sort, int index = 1, int size = 10)
        {
            string pageSQL = @"SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY {1}) ROW_INDEX,{0}) AS  T0 WHERE ROW_INDEX BETWEEN {2} AND {3}";
            if (sql.StartsWith("SELECT", StringComparison.CurrentCultureIgnoreCase))
            {
                sql = sql.Replace("SELECT", String.Empty);
            }
            if (index < 1)
                index = 1;
            int startIndex = (index - 1) * size + 1;
            int endIndex = index * size;
            return string.Format(pageSQL, sql, sort, startIndex, endIndex);

        }

        static string BuildTotalSQL(string sql)
        {
            var selectCount = new StringBuilder("SELECT COUNT(1) ");
            return selectCount.Append(sql.Remove(0, sql.IndexOf("FROM", StringComparison.CurrentCultureIgnoreCase))).ToString();
        }

        IEnumerable<T> GetPagedList<T>(out int total, int index, int size, string sql, string sort, object param) where T : class
        {

            using (var connection = GetDbConnection())
            {
                var totalSQL = BuildTotalSQL(sql);
                var pageSQL = BuildPageSQL(sql, sort, index, size);
                total = connection.Query<int>(totalSQL, param).FirstOrDefault();
                return connection.Query<T>(pageSQL, param);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="sort"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        IEnumerable<T> GetQueryList<T>(string sql, string sort, object param) where T : class
        {
            if (String.IsNullOrWhiteSpace(sort))
                sql = sql + " ORDER BY " + sort;
            using (var connection = GetDbConnection())
            {
                return connection.Query<T>(sql, param);
            }
        }

        #endregion

    }
}
